/*
 * @Author: 369886629@qq.com 369886629@qq.com
 * @Date: 2025-03-12 16:59:36
 * @LastEditors: 369886629@qq.com 369886629@qq.com
 * @LastEditTime: 2025-04-10 09:50:27
 * @FilePath: \sqeybusiness-h5\src\utils\wechat.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

    // 微信配置参数（需替换为实际值）
    const WX_CONFIG = {
        //APPID: 'wx4cb99b1bdc687e06', //测试
        APPID: 'wxd81a6bd295facda3', //正式
        REDIRECT_URI: encodeURIComponent(window.location.href),
        //SCOPE: 'snsapi_base', // 静默授权 
        SCOPE:'snsapi_userinfo', // 授权登录
        //APPSECRET:'390f677950880eb8c15be7e6c5d05e61' , //测试
        APPSECRET:'97bceab2781722d49b12406bdb24ffd2'    //正式
    }

    export default {
            /**
             * 获取微信OpenID
             * @returns {Promise<string>} OpenID
             */
            async getOpenId() {
            // 优先从本地存储获取
            const cachedOpenId = localStorage.getItem('wx_openid')
            if (cachedOpenId) return cachedOpenId
            // 获取授权code
            const code = await this._getAuthCode()
            debugger
            // 通过code换取openid
            return {code:code} 
        },

        /**
         * 获取微信授权code
         * @private
         */
        _getAuthCode() {
            return new Promise((resolve, reject) => {
                /*  
                if (!this._isWeixinBrowser()) {
                    return reject(new Error('请在微信客户端中打开'))
                } */
                // 从URL中获取code参数
                const code = this._getUrlParam('code')
                if (code) {
                    resolve(code)
                } else {
                    // 跳转微信授权页面
                    const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WX_CONFIG.APPID}&redirect_uri=${WX_CONFIG.REDIRECT_URI}&response_type=code&scope=${WX_CONFIG.SCOPE}#wechat_redirect`
                    window.location.href = authUrl
                } 
            })
        },

        /**
         * 检查是否微信浏览器
         * @private
         */
        _isWeixinBrowser() {
            const ua = navigator.userAgent.toLowerCase()
            return ua.includes('micromessenger')
        },

        /**
         * 获取URL参数
         * @param {string} name 参数名
         * @private
         */
        _getUrlParam(name) {
            const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`)
            const match = window.location.search.substr(1).match(reg)
            return match ? decodeURIComponent(match[2]) : null
        },
    }
    